package cn.com.dreamtouch.magicbox_general_ui.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import cn.com.dreamtouch.magicbox_general_ui.R;


/**
 * @author ZJJ
 */
public class AddAndSubView extends LinearLayout {

    Context context;
    View mainLinearLayout;   //主View，即AddAndSubView
    LinearLayout leftLinearLayout;   //内部左view
    LinearLayout centerLinearLayout;   //中间view
    LinearLayout rightLinearLayout;  //内部右view
    OnNumChangeListener onNumChangeListener;
    Button addButton;
    Button subButton;
    EditText editText;
    int num;                   //editText中的数值
    int editTextLayoutWidth;   //editText视图的宽度
    int editTextLayoutHeight;  //editText视图的宽度
    int editTextMinimumWidth;  //editText视图的最小宽度
    int editTextMinimumHeight; //editText视图的最小高度
    int editTextMinHeight;  //editText文本区域的最小高度
    int editTextHeight;  //editText文本区域的高度

    private int cusStyle;//数值为0时样式

    /**
     * 构造方法
     */
    public AddAndSubView(Context context) {
        super(context);
        this.context = context;
        num = 0;
        control();
    }

    public AddAndSubView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        num = 0;

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.add_and_sub);
        cusStyle = a.getInteger(R.styleable.add_and_sub_cusStyle, 0);

        control();
    }

    /**
     *
     */
    private void control() {
        initialise();          //实例化内部view
        setViewListener();
    }


    /**
     * 实例化内部View
     */
    private void initialise() {

        mainLinearLayout = View.inflate(context, R.layout.ll_add_sub, null);
        leftLinearLayout = (LinearLayout) mainLinearLayout.findViewById(R.id.ll_left);
        centerLinearLayout = (LinearLayout) mainLinearLayout.findViewById(R.id.ll_center);
        rightLinearLayout = (LinearLayout) mainLinearLayout.findViewById(R.id.ll_right);
        addButton = (Button) mainLinearLayout.findViewById(R.id.btn_add);
        subButton = (Button) mainLinearLayout.findViewById(R.id.btn_sub);
        editText = (EditText) mainLinearLayout.findViewById(R.id.edt_num);

        addView(mainLinearLayout);

        addButton.setTag("+");
        subButton.setTag("-");
        //设置输入类型为数字
        editText.setInputType(android.text.InputType.TYPE_CLASS_NUMBER);
        editText.setText(String.valueOf(num));
    }

    /**
     * 设置EditText视图和文本区域宽高
     */
    private void setTextWidthHeight() {
        float fPx;

        //设置视图最小宽度
        if (editTextMinimumWidth < 0) {
            // 将数据从dip(即dp)转换到px，第一参数为数据原单位（此为DIP），第二参数为要转换的数据值
            fPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                    80f, context.getResources().getDisplayMetrics());
            editTextMinimumWidth = Math.round(fPx);
        }
        editText.setMinimumWidth(editTextMinimumWidth);

        //设置文本区域高度
        if (editTextHeight > 0) {
            if (editTextMinHeight >= 0 && editTextMinHeight > editTextHeight) {
                editTextHeight = editTextMinHeight;
            }
            editText.setHeight(editTextHeight);
        }

        //设置视图高度
        if (editTextLayoutHeight > 0) {
            if (editTextMinimumHeight > 0 &&
                    editTextMinimumHeight > editTextLayoutHeight) {
                editTextLayoutHeight = editTextMinimumHeight;
            }

            LayoutParams layoutParams = (LayoutParams) editText.getLayoutParams();
            layoutParams.height = editTextLayoutHeight;
            editText.setLayoutParams(layoutParams);
        }

        //设置视图宽度
        if (editTextLayoutWidth > 0) {
            if (editTextMinimumWidth > 0 &&
                    editTextMinimumWidth > editTextLayoutWidth) {
                editTextLayoutWidth = editTextMinimumWidth;
            }

            LayoutParams layoutParams = (LayoutParams) editText.getLayoutParams();
            layoutParams.width = editTextLayoutWidth;
            editText.setLayoutParams(layoutParams);
        }
    }

    /**
     * 设置editText中的值
     *
     * @param num
     */
    public void setNum(int num) {
        this.num = num;
        editText.setText(String.valueOf(num));
    }

    /**
     * 获取editText中的值
     *
     * @return
     */
    public int getNum() {
        if (editText.getText().toString() != null) {
            return Integer.parseInt(editText.getText().toString());
        } else {
            return 0;
        }
    }

    /**
     * 设置文本变化相关监听事件
     */
    private void setViewListener() {
        addButton.setOnClickListener(new OnButtonClickListener());
        subButton.setOnClickListener(new OnButtonClickListener());
        editText.addTextChangedListener(new OnTextChangeListener());
    }

    public void setBtnPlusDisabled() {
        addButton.setOnClickListener(null);
    }

    /**
     * 加减按钮事件监听器
     *
     * @author ZJJ
     */
    class OnButtonClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            String numString = editText.getText().toString();
            if (numString == null || numString.equals("")) {
                num = 0;
                editText.setText("0");
            } else {
                if (v.getTag().equals("+")) {
                    if (++num < 1)  //先加，再判断
                    {
                        num--;
                    } else {
                        editText.setText(String.valueOf(num));
                    }
                } else if (v.getTag().equals("-")) {
                    if (--num < 0)  //先减，再判断
                    {
                        num++;
                    } else {
                        editText.setText(String.valueOf(num));
                    }
                }
            }
            if(onNumChangeListener == null ){
                return;
            }
            onNumChangeListener.onNumChange(AddAndSubView.this, num);
        }
    }


    /**
     * EditText输入变化事件监听器
     *
     * @author ZJJ
     */
    class OnTextChangeListener implements TextWatcher {

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(s.toString()) && onNumChangeListener != null) {
                if (cusStyle == 0) return;

                if (Integer.parseInt(s.toString()) == 0) {
                    subButton.setVisibility(INVISIBLE);
                    editText.setVisibility(INVISIBLE);
                } else {
                    subButton.setVisibility(VISIBLE);
                    editText.setVisibility(VISIBLE);
                }

            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

    }

    public void setOnNumChangeListener(OnNumChangeListener onNumChangeListener) {
        this.onNumChangeListener = onNumChangeListener;
    }

    public interface OnNumChangeListener {
        /**
         * 输入框中的数值改变事件
         *
         * @param view 整个AddAndSubView
         * @param num  输入框的数值
         */
        public void onNumChange(View view, int num);
    }

}
